﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BaseCoder.Utility;
using System.IO;
using System.Text.RegularExpressions;
using System.Configuration;

namespace BaseCoder.BLLCoder
{
    public class BLLCreate
    {
        private ProjectConfig config = null;
        public BLLCreate(ProjectConfig config)
        {
            this.config = config;
        }
        public void CreateBLL()
        {
            Table[] tables = DBHelper.GetTables(config.ConectionString);
            if (tables.Length <= 0) return;
            for (int i = 0; i < tables.Length; i++)
            {
                CreateBLLByTable(config.ConectionString, tables[i]);
                Console.WriteLine(tables[i].Name + " BLL逻辑层基本方法生成结束");
            }
        }
        public void CreateBLLByTable(string connectionString, Table table)
        {

            string bllName = BLLFileName(table.Name);
            string objectName = bllName.Replace("BLL", "");
            string modelName = objectName.Substring(0, 1).ToLower() + objectName.Substring(1);


            if (ConfigurationManager.AppSettings["BLLCover"] == "0" && File.Exists(config["DALSavePath"] + bllName + ".cs"))
            {
                Console.WriteLine(bllName + " 已存在并且不可覆盖");
                return;
            }
            string DBConnetionName = ConfigurationManager.AppSettings["DBConnetionName"];
            TableColumn[] columns = DBHelper.GetColumns(connectionString, table.Name);
            if (columns.Length <= 0) return;
            StringBuilder sb = new StringBuilder();
            StringBuilder tempsb = new StringBuilder();
            sb.Append(GetDescription(table.Name, table.Description));
            sb.Append(GetNamespace());
            sb.AppendLine("namespace " + config["BLLNamespace"] + "");
            sb.AppendLine("{");
            if (!string.IsNullOrEmpty(table.Description))
            {
                sb.AppendLine("     /// <summary>");
                sb.AppendLine("     /// " + FormatDescrition(table.Description) + "");
                sb.AppendLine("     /// </summary>");
            }
            sb.Append("     public class " + bllName + "\n");
            sb.Append("     {\n");
            /*各种数据库操作方法 Start*/
            if (config["IsFactory"] == "1")
            {
                sb.Append("         private static I" + objectName + " " + modelName + "DAL = DataAccess.Create" + objectName + "();\n");
            }
            else
            {
                sb.Append("         private static " + objectName + "DAL " + modelName + "DAL = new " + objectName + "DAL();\n");
            }


            #region 添加数据的方法
            sb.Append("         #region 添加\n");
            sb.Append("         /// <summary>\n");
            sb.Append("         /// 添加 " + table.Name + "\n");
            sb.Append("         /// </summary>\n");
            sb.Append("         /// <param name=\"model\">" + table.Name + "实体</param>\n");
            sb.Append("         /// <returns>新记录主键Id</returns>\n");
            sb.Append("         public int Insert" + objectName + "(" + table.Name + " " + modelName + ")\n");
            sb.Append("         {\n");
            sb.AppendLine("             return " + modelName + "DAL.Insert(" + modelName + ");");
            sb.Append("         }\n");
            sb.Append("          #endregion\n");
            sb.Append("\n");
            tempsb.Remove(0, tempsb.Length);
            #endregion

            #region 编辑数据
            sb.AppendLine("         #region 编辑数据");
            sb.AppendLine("         /// <summary>");
            sb.AppendLine("         /// 编辑实体");
            sb.AppendLine("         /// </summary>");
            sb.AppendLine("         /// <param name=\"model\">" + table.Name + "实体</param>");
            sb.AppendLine("         /// <returns>修改结果</returns>");
            sb.AppendLine("         public bool Edit" + objectName + "(" + table.Name + " " + modelName + ")");
            sb.AppendLine("         {");

            sb.AppendLine("              return " + modelName + "DAL.Edit(" + modelName + ");");
            sb.AppendLine("         }");
            sb.AppendLine("         #endregion");
            #endregion


            #region 修改字段
            sb.Append("         #region 修改字段\n");
            sb.Append("         /// <summary>\n");
            sb.Append("         /// 修改字段\n");
            sb.Append("         /// </summary>\n");
            sb.Append("         /// <param name=\"fields\">需要更新的数据</param>\n");
            sb.Append("         /// <param name=\"where\">更新条件</param>\n");
            sb.Append("         /// <returns></returns>\n");
            sb.Append("         public bool UpdateFields(string fields, string where)\n");
            sb.Append("         {\n");
            sb.Append("             return " + modelName + "DAL.Update(fields,where);\n");
            sb.Append("         }\n");
            sb.Append("         #endregion\n");
            sb.Append("\n");
            #endregion

            #region 删除数据
            sb.Append("         #region 删除\n");
            sb.Append("         /// <summary>\n");
            sb.Append("         /// 真删除" + table.Name + " 禁止调用\n");
            sb.Append("         /// </summary>\n");
            sb.Append("         /// <param name=\"where\">删除条件</param>\n");
            sb.Append("         /// <returns>执行结果</returns>\n");
            sb.Append("         private bool TDelete" + objectName + "(int " + modelName + "Id)\n");
            sb.Append("         {\n");
            sb.Append("             return " + modelName + "DAL.Delete(\"" + modelName + "Id=\"+" + modelName + "Id+\"\");\n");
            sb.Append("          }\n");
            sb.Append("         /// <summary>\n");
            sb.Append("         /// 删除" + table.Name + "-把IsDeleted设为True\n");
            sb.Append("         /// </summary>\n");
            sb.Append("         /// <param name=\"where\">删除条件</param>\n");
            sb.Append("         /// <returns>执行结果</returns>\n");
            sb.Append("         private bool Delete" + objectName + "(int " + modelName + "Id)\n");
            sb.Append("         {\n");
            sb.Append("             return " + modelName + "DAL.Update(\"IsDeleted=1\",\"" + modelName + "Id=\"+" + modelName + "Id+\"\");\n");
            sb.Append("          }\n");
            sb.Append("         #endregion\n");

            #endregion

            #region 获得一个数据实体

            sb.Append("         #region 获得单个对象\n");
            sb.Append("         /// <summary>\n");
            sb.Append("         /// 获得一个" + table.Name + "实体\n");
            sb.Append("         /// </summary>\n");
            sb.Append("         /// <param name=\"where\">查询条件 不需要带Where</param>\n");
            sb.Append("         /// <returns></returns>\n");
            sb.Append("         public " + table.Name + " Get" + objectName + "(int " + modelName + "Id)\n");
            sb.Append("         {\n");
            sb.Append("             return " + modelName + "DAL.Get(\"" + modelName + "Id=\"+" + modelName + "Id);\n");
            sb.Append("         }\n");
            sb.Append("         #endregion\n");
            sb.Append("\n");

            #endregion

            #region 分页数据查询
            sb.Append("         #region 分页查询\n");
            sb.Append("         /// <summary>\n");
            sb.Append("         /// 分页查询\n");
            sb.Append("         /// </summary>\n");
            sb.Append("         /// <param name=\"record\">记录数</param>\n");
            sb.Append("         /// <param name=\"curPage\">当前页</param>\n");
            sb.Append("         /// <param name=\"pageSize\">页面大小</param>\n");
            sb.Append("         /// <param name=\"orderBy\">排序条件</param>\n");
            sb.Append("         /// <param name=\"where\">条件</param>\n");
            sb.Append("         /// <returns></returns>\n");
            sb.Append("         public IList<" + table.Name + "> Get" + objectName + "List(out int record, int curPage, int pageSize, string orderBy, string where)\n");
            sb.Append("         {\n");
            sb.Append("             return " + modelName + "DAL.GetList(out record,curPage,pageSize,orderBy,where);\n");
            sb.Append("         }\n");
            sb.Append("         #endregion\n");
            sb.Append("\n");
            #endregion

            /*各种数据库操作方法 End*/
            sb.Append("     }\n");
            sb.Append("}\n");

            if (File.Exists(config["BLLSavePath"] + bllName + ".cs")) File.Delete(config["BLLSavePath"] + bllName + ".cs");
            FileStream fs = new FileStream(config["BLLSavePath"] + bllName + ".cs", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
            StreamWriter sw = new StreamWriter(fs);
            sw.Flush();
            sw.BaseStream.Seek(0, SeekOrigin.End);
            sw.WriteLine(sb.ToString());
            sw.Flush();
            sw.Close();
        }

        public string BLLFileName(string tableName)
        {
            if (string.IsNullOrEmpty(tableName)) throw new Exception("表名不正确！");
            if (tableName.IndexOf("_") < 0) return tableName + "BLL";
            string fileName = "";
            string[] tableNames = tableName.Split('_');
            if (tableNames.Length > 3)
            {
                for (int i = 2; i < tableNames.Length; i++)
                {
                    fileName += tableNames[i];
                }
            }
            else if (tableNames.Length > 2)
            {
                fileName = tableNames[2];
            }
            else
            {
                fileName = tableNames[1];
            }

            return fileName + "BLL";
        }

        public string GetDescription(string tableName, string tableDescription)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("/*");
            sb.AppendLine("* Copyright (C) " + DateTime.Now.ToString("yyyy") + " " + config["CompanyName"] + "  版权所有");
            sb.AppendLine("* 文件名：" + tableName + "DAL.cs ");
            sb.AppendLine("* 文件功能描述：" + FormatDescrition(tableDescription) + "数据库操作类 ");
            sb.AppendLine("* 创建标示：lan @ " + DateTime.Now.ToString("yyyyMMdd HH:mm:ss") + " ");
            sb.AppendLine("*/");
            return sb.ToString();
        }
        public string GetNamespace()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("using System;");
            sb.AppendLine("using System.Collections.Generic;");
            sb.AppendLine("using System.Linq;");
            if (config["IsFactory"] == "1")
            {
                sb.AppendLine("using " + config["IDAL"] + ";");
                sb.AppendLine("using " + config["DALFactory"] + ";");
            }
            else
            {
                sb.AppendLine("using " + config["DALNamespace"] + ";");
            }
            sb.AppendLine("using System.Data.SqlClient;");
            sb.AppendLine("using " + config["ModelNamespace"] + ";");
            sb.AppendLine("using System.Text;\r");
            sb.AppendLine("");



            return sb.ToString();
        }
        public string FormatDescrition(string desp)
        {
            Regex regex = new Regex("\r\n", RegexOptions.IgnoreCase);
            return regex.Replace(desp, "");
        }
    }
}
